<template>
  <el-form 
    ref="formRef" 
    :model="formData" 
    :rules="rules" 
    label-position="top" 
    class="courier-form"
    v-loading="loading"
  >
    <div class="form-header">
      <h3>{{ isEdit ? '编辑配送员' : '新增配送员' }}</h3>
    </div>
    
    <div class="form-body">
      <div class="basic-info">
        <h4>基本信息</h4>
        
        <div class="avatar-upload">
          <el-avatar :size="80" :src="formData.avatar">
            {{ formData.name ? formData.name.substring(0, 1) : '头' }}
          </el-avatar>
          <el-button size="small" @click="handleAvatarUpload">
            上传头像
          </el-button>
          <input 
            type="file" 
            ref="avatarInput" 
            style="display: none" 
            accept="image/*"
            @change="onAvatarSelected" 
          />
        </div>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="工号" prop="jobNumber">
              <el-input 
                v-model="formData.jobNumber" 
                placeholder="不填写将自动生成" 
                :disabled="isEdit" 
              />
              <div class="form-tip">格式：C+年月日+4位数字，例如：C202412010001</div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱地址（可选）" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配送区域" prop="area">
              <el-select v-model="formData.area" placeholder="请选择配送区域" style="width: 100%">
                <el-option label="华东地区" value="华东地区" />
                <el-option label="华南地区" value="华南地区" />
                <el-option label="华北地区" value="华北地区" />
                <el-option label="西南地区" value="西南地区" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="工作状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择工作状态" style="width: 100%">
                <el-option label="在职" value="active" />
                <el-option label="停职" value="suspended" />
                <el-option label="离职" value="inactive" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" v-if="isEdit">
          <el-col :span="12">
            <el-form-item label="累计派送量" prop="deliveryCount">
              <el-input-number 
                v-model="formData.deliveryCount" 
                :min="0" 
                style="width: 100%" 
                placeholder="累计派送量"
                disabled
              />
              <div class="form-tip">累计派送量由系统自动计算，不可手动修改</div>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="入职日期" prop="entryDate">
              <el-date-picker 
                v-model="formData.entryDate"
                type="date"
                placeholder="选择入职日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" v-if="!isEdit">
          <el-col :span="12">
            <el-form-item label="入职日期" prop="entryDate">
              <el-date-picker 
                v-model="formData.entryDate"
                type="date"
                placeholder="选择入职日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      
      <div v-if="isEdit" class="system-info">
        <h4>系统信息</h4>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="配送员ID">
              <el-input :value="formData.id" disabled />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="关联用户ID">
              <el-input :value="formData.userId" disabled />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="创建时间">
              <el-input :value="formatDateTime(formData.createDate)" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
    
    <div class="form-footer">
      <el-button @click="emit('cancel')">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">
        {{ loading ? '保存中...' : '保存' }}
      </el-button>
    </div>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { addCourier, updateCourier, type Courier, type AddCourierRequest, type UpdateCourierRequest } from '@/api/courier'

const props = defineProps<{
  courierData?: Courier
  isEdit: boolean
}>()

// 页面状态
const loading = ref(false)

// 表单数据
const formData = reactive<{
  id?: number
  userId?: number
  name: string
  phone: string
  email?: string
  area: string
  status: 'active' | 'suspended' | 'inactive'
  jobNumber?: string
  deliveryCount?: number
  entryDate?: string
  createDate?: string
  updateDate?: string
  avatar?: string
}>({
  name: '',
  phone: '',
  email: '',
  area: '',
  status: 'active',
  jobNumber: '',
  deliveryCount: 0,
  entryDate: ''
})

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请选择配送区域', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择工作状态', trigger: 'change' }
  ],
  jobNumber: [
    { pattern: /^C\d{8}\d{4}$/, message: '工号格式为C+年月日+4位数字', trigger: 'blur' }
  ]
})

// 表单引用
const formRef = ref<FormInstance>()

// 头像上传引用
const avatarInput = ref<HTMLInputElement>()

// 头像上传处理
const handleAvatarUpload = () => {
  avatarInput.value?.click()
}

// 头像选择处理
const onAvatarSelected = (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (file) {
    // 这里可以添加头像上传逻辑
    // 暂时设置为本地预览
    const reader = new FileReader()
    reader.onload = (e) => {
      formData.avatar = e.target?.result as string
    }
    reader.readAsDataURL(file)
  }
}

// 格式化时间
const formatDateTime = (dateTime?: string) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 监听props变化，更新表单数据
watch(() => props.courierData, (newValue) => {
  if (newValue && Object.keys(newValue).length > 0) {
    // 复制数据到表单
    Object.assign(formData, newValue)
  }
}, { immediate: true, deep: true })

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) {
    ElMessage.error('请完善表单信息')
    return
  }
  
  loading.value = true
  try {
    if (props.isEdit && formData.id) {
      // 编辑模式
      const updateData: UpdateCourierRequest = {
        name: formData.name,
        phone: formData.phone,
        email: formData.email,
        area: formData.area,
        status: formData.status,
        entryDate: formData.entryDate
      }
      
      if (formData.jobNumber) {
        updateData.jobNumber = formData.jobNumber
      }
      
      const response = await updateCourier(formData.id, updateData)
      if (response.code === 200) {
        ElMessage.success('更新配送员成功')
        emit('save', { ...formData })
      } else {
        ElMessage.error(response.message || '更新失败')
      }
    } else {
      // 新增模式
      const addData: AddCourierRequest = {
        name: formData.name,
        phone: formData.phone,
        email: formData.email,
        area: formData.area,
        status: formData.status
      }
      
      if (formData.jobNumber) {
        addData.jobNumber = formData.jobNumber
      }
      
      const response = await addCourier(addData)
      if (response.code === 200) {
        ElMessage.success('创建配送员成功')
        emit('save', { ...formData })
      } else {
        ElMessage.error(response.message || '创建失败')
      }
    }
  } catch (error: any) {
    console.error('保存配送员失败:', error)
    ElMessage.error(error.message || '操作失败，请重试')
  } finally {
    loading.value = false
  }
}

// 定义组件事件
const emit = defineEmits<{
  save: [courier: any]
  cancel: []
}>()

// 组件挂载时初始化
onMounted(() => {
  // 如果是新增，设置默认的入职日期为今天
  if (!props.isEdit && !formData.entryDate) {
    formData.entryDate = new Date().toISOString().split('T')[0]
  }
})
</script>

<style scoped>
.courier-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.form-header {
  margin-bottom: 24px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 16px;
}

.form-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.form-body {
  margin-bottom: 24px;
}

.form-body h4 {
  font-size: 16px;
  font-weight: 600;
  color: #409EFF;
  margin: 0 0 16px 0;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
}

.system-info {
  margin-top: 24px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.system-info h4 {
  color: #909399;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style> 